package com.ctyun.xstore.vod.internal;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

/**
 * Use this builder to build a OkHttpClient that trust all certificates.
 * 
 * NOTICE: this may cause security problems!!
 * 
 * @author keijack
 *
 */
public class OkHttpClientBuilder {

	private class TrustAllCertificateManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
	}

	private static volatile OkHttpClient client;

	private final OkHttpClient.Builder builder;

	public OkHttpClientBuilder() {
		builder = new OkHttpClient.Builder();
		try {
			TrustAllCertificateManager certificateManager = new TrustAllCertificateManager();

			SSLContext sslCtx = SSLContext.getInstance("TLSv1.3");
			sslCtx.init(null, new TrustManager[] { certificateManager }, new SecureRandom());
			SSLSocketFactory ssfFactory = sslCtx.getSocketFactory();

			builder.sslSocketFactory(ssfFactory, certificateManager).hostnameVerifier((hostname, session) -> true);
		} catch (Exception e) {
			// ignore exception
		}
	}

	public static OkHttpClient singaletonClient() {
		if (client == null) {
			synchronized (OkHttpClientBuilder.class) {
				if (client == null)
					client = new OkHttpClientBuilder().build();
			}
		}
		return client;
	}

	public OkHttpClient build() {
		return builder.retryOnConnectionFailure(true).connectTimeout(10, TimeUnit.SECONDS)
				.readTimeout(10, TimeUnit.SECONDS).callTimeout(100, TimeUnit.SECONDS).build();
	}

}
